use std::collections::HashMap;

use common::error::MyError;
use entity::resource;
use model::resource::{CreateResource, ResourcePage, ResourceTree};

use crate::auth_service::build_all_resource;
use crate::base::BaseService;
use crate::manager::resource::ResourceManager;

pub struct ResourceService {}

impl
    BaseService<
        i64,
        resource::Model,
        ResourcePage,
        CreateResource,
        resource::Model,
        ResourceManager,
    > for ResourceService
{
}

impl ResourceService {
    fn build_child_resource_tree(
        parent_resource: &resource::Model,
        parent_key_map: &HashMap<i64, Vec<resource::Model>>,
    ) -> Result<Vec<ResourceTree>, MyError> {
        let mut children_tree_list = Vec::new();
        let child_resources = parent_key_map.get(&parent_resource.id);
        match child_resources {
            //如果存在子节点则继续遍历
            Some(child_resources) => {
                //构建子节点
                for child_resource in child_resources {
                    let tmp_child_resource = child_resource.clone();
                    let child = ResourceService::build_child_resource_tree(
                        &child_resource,
                        parent_key_map,
                    )?;
                    let children_tree = ResourceTree {
                        parent_id: tmp_child_resource.parent_id,
                        key: tmp_child_resource.id,
                        title: tmp_child_resource.resource_name.unwrap(),
                        children: child,
                    };
                    children_tree_list.push(children_tree)
                }
            }
            _ => {}
        }
        //返回构建好的节点
        Ok(children_tree_list)
    }
    pub async fn resource_tree() -> Result<Vec<ResourceTree>, MyError> {
        let mut result_vec = Vec::new();
        let list = ResourceManager::get_resource_all_list().await?;
        let all_resource_map = build_all_resource(&list)?;
        let root_resource = all_resource_map.0;
        let parent_key_map: HashMap<i64, Vec<resource::Model>> = all_resource_map.1;
        //遍历所有根节点，依次构建每个节点和对应的子节点
        for resource in root_resource {
            let child_menu =
                ResourceService::build_child_resource_tree(&resource, &parent_key_map)?;
            //构建根节点
            result_vec.push(ResourceTree {
                parent_id: resource.parent_id,
                key: resource.id,
                title: resource.resource_name.unwrap(),
                children: child_menu,
            })
        }
        Ok(result_vec)
    }
}
